import axios from 'axios' 
import ElementUI from 'element-ui';
/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * 200 成功 201已创建 401未授权
 */
export function get(url, params){
    return new Promise((resolve, reject) =>{	
        axios.get(url, {
            params: params
        }).then(res => {
			/** 
			if(res.data.code == 200) {	//	成功
            	resolve(res.data.data);
			} else if(res.data.code == 201) {	//	已创建
				ElementUI.Message.info(res.data.msg);
			} else if(res.data.code == 401) {	//	未授权
				ElementUI.Message.info(res.data.msg);
			} 
			*/
			if(res.data.code == 403) {	//	禁止访问token失效
				ElementUI.Message.info(res.data.msg);
				window.location.href = '/'
				localStorage.clear();
			} else if(res.data.code == 404) {	//	404
				ElementUI.Message.info(res.data.msg);
				window.location.href = '/404'
			} else {
				resolve(res.data);
			};
        }).catch(err =>{
			if( err && err.response && err.response.status == 403) {
				ElementUI.Message.error('token失效，请重新登录');
				window.location.href = '/'
				localStorage.clear();
				return false;
			}
            reject(err.data)
    	})
	});
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * 200 成功 201已创建 401未授权
 */
export function post(url, params = {}) {
    return new Promise((resolve, reject) => {
         axios.post(url, params)
        .then(res => {
			/** 
			if(res.data.code == 200) {	//	成功
            	resolve(res.data);
			} else if(res.data.code == 201) {	//	已创建
				ElementUI.Message.info(res.data.msg);
			} else if(res.data.code == 401) {	//	未授权
				ElementUI.Message.info(res.data.msg);
			} */
			if(res.data.code == 403) {	//	禁止访问token失效
				ElementUI.Message.info(res.data.msg);
				window.location.href = '/'
				localStorage.clear();
			} else if(res.data.code == 404) {	//	404
				ElementUI.Message.info(res.data.msg);
				window.location.href = '/404'
			} else {
				resolve(res.data);
			};
        })
        .catch(err =>{
			if( err && err.response && err.response.status == 403) {
				ElementUI.Message.error('token失效，请重新登录');
				window.location.href = '/'
				localStorage.clear();
				return false;
			}
            reject(err.data)
        })
    });
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url,data = {}){
return new Promise((resolve,reject) => {
	axios.patch(url,data)
		.then(response => {
			if(response.data.code == 403) {
				ElementUI.Message({
					message: 'token失效，请重新登录',
					type: 'error'
				});
				window.location.href = '/'
				localStorage.clear();
				return false
			}
			resolve(response.data);
		},err => {
			if( err && err.response && err.response.status == 403) {
				ElementUI.Message({
					message: 'token失效，请重新登录',
					type: 'error'
				});
				window.location.href = '/'
				localStorage.clear();
				return false;
			}
			reject(err)
		})
})
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url,data = {}){
return new Promise((resolve,reject) => {
	axios.put(url,data)
		.then(res => {
			if(res.data.code == 403) {
				ElementUI.Message({
					message: 'token失效，请重新登录',
					type: 'error'
				});
				window.location.href = '/'
				localStorage.clear();
				return false
			}
			resolve(res.data);
		},err => {
			if( err && err.response && err.response.status == 403) {
				ElementUI.Message({
					message: 'token失效，请重新登录',
					type: 'error'
				});
				window.location.href = '/'
				localStorage.clear();
				return false;
			}
			reject(err)
		})
})
}

/**
 * 封装deleFn请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function deleteFn(url, params) {
	return new Promise((resolve, reject) => {
		axios.delete(url, {params: params})
			.then(res => {
				if(res.data.code == 403) {
					ElementUI.Message({
						message: 'token失效，请重新登录',
						type: 'error'
					});
					window.location.href = '/'
					localStorage.clear();
					return false
				}
				resolve(res.data);
			})
			.catch(err =>{
				if( err && err.response && err.response.status == 403) {
					ElementUI.Message({
						message: 'token失效，请重新登录',
						type: 'error'
					});
					window.location.href = '/'
					localStorage.clear();
					return false;
				}
				reject(err.data)
			})
	});
}


/**
	 *  格式数据
	 *  @filterVal  格式头
	 *  @tableData  用来格式的表格数据
	 */
 export function formatJson(filterVal, tableData) {
	return tableData.map(v => {
		return filterVal.map(j => {
				return v[j]
			})
		}
	)
}

/*****时间转化 */
export function formatDate (date, fmt) {
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
	}
	let o = {
		'M+': date.getMonth() + 1,
		'd+': date.getDate(),
		'h+': date.getHours(),
		'm+': date.getMinutes(),
		's+': date.getSeconds()
	}
	for (let k in o) {
		if (new RegExp(`(${k})`).test(fmt)) {
			let str = o[k] + ''
			fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str))
		}
	}
	return fmt
}

function padLeftZero (str) {
	return ('00' + str).substr(str.length)
}

//	相差多少天
export function DateDiffn (targetDate) {
	let date1 = new Date(targetDate);
	let date2 = new Date();
	date1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
	date2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
	const diff = date1.getTime() - date2.getTime(); //目标时间减去当前时间
	const diffDate = diff / (24 * 60 * 60 * 1000);
	return diffDate;
  }
// 封装一个判断图片文件后缀名的方法
export function isImage(fileName) {
	if (typeof fileName !== 'string') return;
	let name = fileName.toLowerCase();
	return name.endsWith('.png') || name.endsWith('.jpeg') || name.endsWith('.jpg') || name.endsWith('.png') || name.endsWith('.bmp');
  }

  // 获取两个日期相差的年月日
  export function formatDateDiff(time1, time2, m) {
	const year1 = time1.getFullYear()
	const year2 = time2.getFullYear()
	const month1 = time1.getMonth() + 1
	const month2 = time2.getMonth() + 1
	const day1 = time1.getDate()
	const day2 = time2.getDate()
	if (year2 === year1) { // 判断两个日期 是否是同年
	  if (month2 - month1 > m) { // 相差是否 在m个月中
		return false
	  } else if (month2 - month1 === m) { // 如果正好为 m月 判断天数
		if (day2 > day1) {
		  return false
		}
	  }
	} else { // 不同年
	  if (year2 - year1 > 1) { 
		return false
	  }
	  else if (year2 - year1 === 1) { 
		if (month2 > m || month1 + m - month2 < 12) {
		  return false
		}
		else if (month1 + m - month2 === 12) { // 正好为m月 判断天数
		  if (day2 > day1) {
			return false
		  }
		}
	  }
	}
	return true
  }


export default {
	get,
	put,
	patch,
	post,
	deleteFn,
	formatJson,
	formatDate,
	DateDiffn,
	isImage,
	formatDateDiff
}